package org.example.zuoye.common;

import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.zuoye.util.JwtUtils;
import org.example.zuoye.util.WebAppUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * @Author xinchen
 * @Date: 2024/08/14/ 10:21
 * @Description 登录拦截器
 */
public class JwtInterceptor implements HandlerInterceptor {

    private final String jwtSecretKey;

    public JwtInterceptor(String jwtSecretKey) {
        this.jwtSecretKey = jwtSecretKey;
    }
    // 前置拦截器
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        // 获取请求头中令牌
        String jwt = req.getHeader("jwt"); //请求头中获取jwt
        //对jwt进行解密
        try {
            //可能会出现很多运行时异常: 过期、错误、非法
            DecodedJWT dj = JwtUtils.decode(jwt, jwtSecretKey);
            return true;
        } catch (Exception e) {
            WebAppUtils.writeJson(resp, Map.of("code",401,"msg","jwt无效"));
            return false;
        }

    }
}
